package Email;
 
import java.util.*;
import java.io.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

import java.util.*;
import java.io.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 * 
 * 感谢来自网友的技术！
 * @author Java in Action 移动互联网
 *
 */

class MailAuthenticator extends Authenticator
{
    //******************************
    //由于发送邮件的地方比较多,
    //下面统一定义用户名,口令.
    //******************************
    public static String HUAWEI_MAIL_USER = "";
    public static String HUAWEI_MAIL_PASSWORD = "";
 
 
    public MailAuthenticator(String username,String password)
    {
    	HUAWEI_MAIL_USER=username;
    	HUAWEI_MAIL_PASSWORD=password;
    }
 
    protected PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication(HUAWEI_MAIL_USER, HUAWEI_MAIL_PASSWORD);
    }
 
}
 
public class SendMail {
 
    //要发送Mail地址
    private String mailTo = null;
    //Mail发送的起始地址
    private String mailFrom = null;
    //SMTP主机地址
    private String smtpHost = null;
    //是否采用调试方式
    private boolean debug = false;
 
    private String messageBasePath = null;
    //Mail主题
    private String subject;
    //Mail内容
    private String msgContent;
 
    private Vector attachedFileList;
    private String mailAccount = null;
    private String mailPass = null;
    private String messageContentMimeType ="text/html; charset=gb2312";
 
    private String mailbccTo = null;
    private String mailccTo = null;
    /**
     * SendMailService 构造子注解。
     */
    public SendMail() {
        super();
   
    }
 
    private void fillMail(Session session,MimeMessage msg) throws IOException, MessagingException{
   
        String fileName = null;
        Multipart mPart = new MimeMultipart();
        if (mailFrom != null) {
            msg.setFrom(new InternetAddress(mailFrom));
            System.out.println("发送人Mail地址："+mailFrom);
        } else {
            System.out.println("没有指定发送人邮件地址！");
            return;
        }
        if (mailTo != null) {
            InternetAddress[] address = InternetAddress.parse(mailTo);
            msg.setRecipients(Message.RecipientType.TO, address);
            System.out.println("收件人Mail地址："+mailTo);
        } else {
            System.out.println("没有指定收件人邮件地址！");
            return;
        }
   
        if (mailccTo != null) {
            InternetAddress[] ccaddress = InternetAddress.parse(mailccTo);
            System.out.println("CCMail地址："+mailccTo);
            msg.setRecipients(Message.RecipientType.CC, ccaddress);
        }
        if (mailbccTo != null) {
            InternetAddress[] bccaddress = InternetAddress.parse(mailbccTo);
            System.out.println("BCCMail地址："+mailbccTo);
            msg.setRecipients(Message.RecipientType.BCC, bccaddress);
        }
        msg.setSubject(subject);
        InternetAddress[] replyAddress = { new InternetAddress(mailFrom)};
        msg.setReplyTo(replyAddress);
        // create and fill the first message part
        MimeBodyPart mBodyContent = new MimeBodyPart();
        if (msgContent != null)
            mBodyContent.setContent(msgContent, messageContentMimeType);
        else
            mBodyContent.setContent("", messageContentMimeType);
        mPart.addBodyPart(mBodyContent);
        // attach the file to the message
        if (attachedFileList != null) {
            for (Enumeration fileList = attachedFileList.elements(); fileList.hasMoreElements();) {
                fileName = (String) fileList.nextElement();
                MimeBodyPart mBodyPart = new MimeBodyPart();
   
                // attach the file to the message
                FileDataSource fds = new FileDataSource(messageBasePath + fileName);
                System.out.println("Mail发送的附件为："+messageBasePath + fileName);
                mBodyPart.setDataHandler(new DataHandler(fds));
                mBodyPart.setFileName(fileName);
                mPart.addBodyPart(mBodyPart);
            }
        }
        msg.setContent(mPart);
        msg.setSentDate(new Date());
    }
    /**
     * 此处插入方法说明。
     */
    public void init()
    {
   
    }
    
    String username;
    String password;
    
    /**
     * 发送e_mail，返回类型为int
     * 当返回值为0时，说明邮件发送成功
     * 当返回值为3时，说明邮件发送失败
     */
    public int sendMail() throws IOException, MessagingException {
        int loopCount;
        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.auth", "true");
   
        MailAuthenticator auth = new MailAuthenticator(username,password);
   
        Session session = Session.getInstance(props, auth);
        session.setDebug(debug);
        MimeMessage msg = new MimeMessage(session);
        Transport trans = null;
        try {
   
            fillMail(session,msg);
            // send the message
            trans = session.getTransport("smtp");
            try {
                trans.connect(smtpHost, MailAuthenticator.HUAWEI_MAIL_USER, MailAuthenticator.HUAWEI_MAIL_PASSWORD);//, HUAWEI_MAIL_PASSWORD);
            } catch (AuthenticationFailedException e) {
                e.printStackTrace();
                System.out.println("连接邮件服务器错误：");
                return 3;
            } catch (MessagingException e) {
                System.out.println("连接邮件服务器错误：");
                return 3;
            }
   
            trans.send(msg);
            trans.close();
   
        } catch (MessagingException mex) {
            System.out.println("发送邮件失败：");
            mex.printStackTrace();
            Exception ex = null;
            if ((ex = mex.getNextException()) != null) {
                System.out.println(ex.toString());
                ex.printStackTrace();
            }
            return 3;
        } finally {
            try {
                if (trans != null && trans.isConnected())
                    trans.close();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
        System.out.println("发送邮件成功！");
        return 0;
    }
    public void setAttachedFileList(java.util.Vector filelist)
    {
        attachedFileList = filelist;
    }
    public void setDebug(boolean debugFlag)
    {
        debug=debugFlag;
    }
    public void setMailAccount(String strAccount) {
        mailAccount = strAccount;
    }
    public void setMailbccTo(String bccto) {
        mailbccTo = bccto;
    }
    public void setMailccTo(String ccto) {
        mailccTo = ccto;
    }
    public void setMailFrom(String from)
    {
        mailFrom=from;
    }
    public void setMailPass(String strMailPass) {
        mailPass = strMailPass;
    }
    public void setMailTo(String to)
    {
        mailTo=to;
    }
    public void setMessageBasePath(String basePath)
    {
        messageBasePath=basePath;
    }
    public void setMessageContentMimeType(String mimeType)
    {
        messageContentMimeType = mimeType;
    }
    public void setMsgContent(String content)
    {
        msgContent=content;
    }
    public void setSMTPHost(String host)
    {
        smtpHost=host;
    }
    public void setSubject(String sub)
    {
        subject=sub;
    }
    
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
    
	/**
	 * 发送一封邮件
	 * @param host smtp服务器
	 * @param username 登录服务器用的用户名
	 * @param password 登录服务器用的密码
	 * @param from 发件人
	 * @param to 收件人
	 * @param subject 标题
	 * @param content 内容（支持HTML）
	 * @return 发送成功返回true并将发送状态输出到控制台，否则返回false并将错误信息输出到控制台
	 * @throws Exception 发生任何异常时抛出
	 */
    public static void send(final String host,final String username,final String password,final String from,final String to,final String subject,final String content) 
    		throws Exception{
        new Thread(){

			@Override
			public void run() {
				System.out.println("MailKernel:邮件线程启动！发送给："+to);
				SendMail sm = new SendMail();
		        sm.setSMTPHost(host);
		        sm.setUsername(username);
		        sm.setPassword(password);
		        sm.setMailFrom(from);
		        sm.setMailTo(to);
		        sm.setMsgContent(content);
		        sm.setSubject(subject);
		        try {
					sm.sendMail();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MessagingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		        System.out.println("MailKernel:邮件线程完成！发送给："+to);
			}
        }.start();;
    }
}
